import { AppTask } from "../../app.task.class";
import { V3proScreen } from "../../../api/v3pro-api/v3pro.api.response.model";
import {
  appConfig,
  GlobalScreenTokens,
  loadScreenTokens,
  saveScreenTokens,
} from "../../../configs/env.config.load";
import { v3proScreenApi } from "../../../api/v3pro-api/v3pro.screen.api";
import { srRegisterApi } from "../../../api/sr-api/sr.api";
import { loggerStdout } from "../../../configs/log.config";

/**
 * 注册屏幕
 */
export class CmdRegisterHandlerTask extends AppTask {
  constructor(private force = false) {
    super();
  }
  __pause(): Promise<boolean> {
    return Promise.resolve(false);
  }

  __restore(): Promise<boolean> {
    return Promise.resolve(false);
  }

  async __run(): Promise<void> {
    try {
      loggerStdout.info("register start [force] %s", this.force);
      const tks = loadScreenTokens();
      console.log(tks);
      if (tks && Object.keys(tks).length && !this.force) {
        loggerStdout.info("token is exist");
        return Promise.resolve();
      }
      const tokens: GlobalScreenTokens = {};
      const screens = await this.__getScreens();
      if (!screens.length) throw new Error("no screen");
      for (const screen of screens) {
        tokens[screen.id] = await this.__register(screen);
      }
      saveScreenTokens(tokens);
      loggerStdout.info("register success");
      loggerStdout.info(tokens);
    } catch (e: any) {
      loggerStdout.error(e?.message || e);
    }
  }

  private async __register(screen: V3proScreen) {
    const body = this.__genRegisterBody(screen);
    const res = await srRegisterApi(body, this.__addCancelToken());
    return res.token;
  }

  private async __getScreens(): Promise<V3proScreen[]> {
    const pages = await v3proScreenApi(this.__addCancelToken());
    return pages.requestDatas;
  }

  /**
   * 生成注册请求体
   * @param screen
   * @private
   */
  private __genRegisterBody(screen: V3proScreen) {
    return {
      id: screen.id,
      assetRegisterKey: appConfig.starriver.server.registerKey,
      name: `${screen.name}-${screen.typeName}`,
      model: "ssads",
      type: screen.type + "",
    };
  }

  __stop(): Promise<boolean> {
    return Promise.resolve(false);
  }
}
